<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <style>
        /* 用户管理页面样式 */
        .user-container {
            padding: 20px;
            max-width: 1200px;
            margin: 0 auto;
        }

        /* 操作栏 */
        .action-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        /* 搜索框 */
        .search-box {
            display: flex;
            align-items: center;
        }

        .search-box input {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-right: 10px;
        }

        .search-box button {
            padding: 8px 16px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .search-box button:hover {
            background-color: #0056b3;
        }

        /* 表格样式 */
        .user-table {
            width: 100%;
            border-collapse: collapse;
            background-color: white;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }

        .user-table th,
        .user-table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }

        .user-table th {
            background-color: #f8f9fa;
            font-weight: 600;
        }

        .user-table tr:hover {
            background-color: #f1f1f1;
        }

        /* 操作按钮 */
        .action-btn {
            padding: 5px 10px;
            margin: 0 5px;
            border: none;
            border-radius: 3px;
            cursor: pointer;
        }

        .ban-btn {
            background-color: #dc3545;
            color: white;
        }

        .unban-btn {
            background-color: #28a745;
            color: white;
        }

        .edit-btn {
            background-color: #ffc107;
            color: black;
        }

        /* 状态样式 */
        .status-banned {
            color: #dc3545;
        }

        .status-active {
            color: #28a745;
        }

        /* 弹窗样式 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
            z-index: 1000;
        }

        .modal-content {
            background-color: white;
            width: 400px;
            padding: 20px;
            border-radius: 8px;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #ddd;
            padding-bottom: 10px;
            margin-bottom: 20px;
        }

        .close-btn {
            font-size: 24px;
            cursor: pointer;
            color: #666;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
        }

        .form-group input,
        .form-group select {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }

        .form-actions {
            text-align: right;
            margin-top: 20px;
        }

        .form-actions button {
            margin-left: 10px;
        }
    </style>
</head>
<body>
    <div class="user-container">
        <div class="action-bar">
            <h2>用户管理</h2>
            <div class="search-box">
                <input type="text" id="search-input" placeholder="输入用户名或ID">
                <button onclick="searchUser()">搜索</button>
            </div>
        </div>

        <!-- 用户表格 -->
        <table class="user-table">
            <thead>
                <tr>
                    <th>用户ID</th>
                    <th>用户名</th>
                    <th>电话号码</th>
                    <th>会员类型</th>
                    <th>会员到期时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="user-body">
                <!-- 数据将通过JavaScript动态生成 -->
            </tbody>
        </table>
    </div>

    <!-- 编辑用户弹窗 -->
    <div id="editModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>编辑用户</h3>
                <span class="close-btn" onclick="closeEditModal()">&times;</span>
            </div>
            <form id="editForm" onsubmit="editUser(event)">
                <div class="form-group">
                    <label for="editUserName">用户名</label>
                    <input type="text" id="editUserName" required>
                </div>
                <div class="form-group">
                    <label for="editPhoneNumber">电话号码</label>
                    <input type="text" id="editPhoneNumber" required>
                </div>
                <div class="form-group">
                    <label for="editPassword">密码</label>
                    <input type="text" id="editPassword" required>
                </div>
                <div class="form-actions">
                    <button type="button" class="action-btn" onclick="closeEditModal()">取消</button>
                    <button type="submit" class="action-btn">保存</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        let currentEditUserId = null; // 当前编辑的用户ID

        document.addEventListener('DOMContentLoaded', () => {
            loadUsers();
        });

        // 加载用户列表
        function loadUsers() {
            axios({
                method: 'get',
                url: 'http://127.0.0.1:5000/admin/users',
                headers: {
                    'Content-Type': 'application/json',
                }
            })
            .then(function (response) {
                if (response.data) {
                    const users = response.data.users;
                    renderUserTable(users);
                    console.log(users);
                } else {
                    alert('获取用户列表失败：' + response.data.message);
                }
            })
            .catch(function (error) {
                console.error('加载用户列表失败：', error);
                if (error.response) {
                    alert('加载用户列表失败：' + (error.response.data.error || '服务器错误'));
                } else {
                    alert('加载用户列表失败：网络错误，请检查连接');
                }
            });
        }

        // 删除用户
        function deleteUser(userId) {
            axios({
                method: 'delete',
                url: `http://127.0.0.1:5000/admin/users/${userId}`,
                headers: {
                    'Content-Type': 'application/json',
                }
            })
            .then(function (response) {
                if (response.data) {
                    alert('用户删除成功！');
                    loadUsers(); // 重新加载用户列表
                } else {
                    alert('用户删除失败：' + response.data.message);
                }
            })
            .catch(function (error) {
                console.log('删除用户失败：', error);
                if (error.response) {
                    alert('删除用户失败：' +'服务器错误');
                    console.log(error.response.data.error);
                } else {
                    alert('删除用户失败：网络错误，请检查连接');
                }
            });
        }

        function renderUserTable(data) {
            const tbody = document.getElementById('user-body');
            tbody.innerHTML = data.map(user => {
                // 格式化日期，只保留年月日
                const formattedDate = user.subscription_end 
                    ? new Date(user.subscription_end).toISOString().split('T')[0] 
                    : "未开通会员";
        
                return `
                    <tr>
                        <td>${user.user_id}</td>
                        <td>${user.username}</td>
                        <td>${user.phone_number}</td>
                        <td>${user.membership_type === 'member' ? '普通会员' : '高级会员'}</td>
                        <td>${formattedDate}</td>
                        <td>
                            <button class="action-btn edit-btn" onclick="openEditModal(${user.user_id})">编辑</button>
                            <button class="action-btn delete-btn" onclick="deleteUser(${user.user_id})">删除</button>
                        </td>
                    </tr>
                `;
            }).join('');
        }

        // 打开编辑弹窗
        function openEditModal(userId) {
            currentEditUserId = userId;
            axios({
                method: 'get',
                url: `http://127.0.0.1:5000/admin/users/${userId}`,
                headers: {
                    'Content-Type': 'application/json',
                }
            })
            .then(function (response) {
                console.log(response.data);
                const user = response.data.basic_info;                ;
                if (user) {
                    document.getElementById('editUserName').value = user.username;
                    document.getElementById('editPhoneNumber').value = user.phone_number;
                    document.getElementById('editPassword').value = ''; // 密码字段通常不显示当前值
                    document.getElementById('editModal').style.display = 'block';
                } else {
                    console.log('用户不存在');
                }
            })
            .catch(function (error) {
                console.log('获取用户信息失败：', error);
                if (error.response) {
                    alert('获取用户信息失败：' + (error.response.data.error || '服务器错误'));
                } else {
                    alert('获取用户信息失败：网络错误，请检查连接');
                }
            });
        }

        // 关闭编辑弹窗
        function closeEditModal() {
            document.getElementById('editModal').style.display = 'none';
            currentEditUserId = null;
        }

        // 编辑用户
        function editUser(event) {
            event.preventDefault();
            const username = document.getElementById('editUserName').value;
            const phoneNumber = document.getElementById('editPhoneNumber').value;
            const password = document.getElementById('editPassword').value;

            axios({
                method: 'put',
                url: `http://127.0.0.1:5000/admin/users/${currentEditUserId}`,
                headers: {
                    'Content-Type': 'application/json',
                },
                data: {
                    username: username,
                    phone_number: phoneNumber,
                    password: password
                }
            })
            .then(function (response) {
                if (response.data) {
                    alert('用户信息更新成功！');
                    loadUsers(); // 重新加载用户列表
                    closeEditModal();
                } else {
                    alert('用户信息更新失败：' + response.data.message);
                }
            })
            .catch(function (error) {
                console.log('更新用户信息失败：', error);
                if (error.response) {
                    alert('更新用户信息失败：' + (error.response.data.error || '服务器错误'));
                } else {
                    alert('更新用户信息失败：网络错误，请检查连接');
                }
            });
        }

        // 搜索用户
        function searchUser() {
            const keyword = document.getElementById('search-input').value.toLowerCase();
            axios({
                method: 'get',
                url: 'http://127.0.0.1:5000/admin/users',
                headers: {
                    'Content-Type': 'application/json',
                }
            })
            .then(function (response) {
                const users = response.data.users;
                const filteredUsers = users.filter(user =>
                    user.username.toLowerCase().includes(keyword) || user.user_id.toString().includes(keyword)
                );
                renderUserTable(filteredUsers);
            })
            .catch(function (error) {
                console.error('搜索用户失败：', error);
                if (error.response) {
                    alert('搜索用户失败：' + (error.response.data.error || '服务器错误'));
                } else {
                    alert('搜索用户失败：网络错误，请检查连接');
                }
            });
        }
    </script>
</body>
</html>